from concurrent.futures.process import ProcessPoolExecutor
from concurrent.futures.thread import ThreadPoolExecutor

import requests,json,random
from binascii import a2b_hex
from Crypto.Cipher import AES
from retry import retry
from loguru import logger

short_link_proxy_pool = [
    #"http://192.168.44.9/get/?token=%qq123456..&qname=spider1&num=",
    "http://192.168.44.9/get/?token=%qq123456..&qname=spider4&num=",
    # "http://192.168.44.9/get/?token=%qq123456..&qname=spider3&num="
]
waiwang_proxies_list = [
    {'https': 'http://192.168.44.119:7890', 'http': 'http://192.168.44.119:7890'},
    {'https': 'http://192.168.44.140:7890', 'http': 'http://192.168.44.140:7890'},
]
long_link_proxy_pool = ['http://192.168.44.9/get/?token=%qq123456..&qname=adsl&num=',
                        # "http://192.168.44.9/get/?token=%qq123456..&qname=HeIp&num="
                        ]

class Proxy_IP:

    def __init__(self):
        self.proxy_list = short_link_proxy_pool
        self.long_proxy_list = long_link_proxy_pool

    # 进行密码解密
    def decrypt(self, text):
        key = "%qq123456.".ljust(16, '\0').encode('utf-8')
        iv_b = ("%qq123456.".ljust(16, '\0')).encode('utf-8')
        cryptos = AES.new(key, AES.MODE_CBC, iv_b)
        plain_text = cryptos.decrypt(a2b_hex(text))
        return bytes.decode(plain_text).rstrip('\0')

    # 进行获取代理内容
    @retry(tries=3, delay=1)
    def get_json(self, url):
        try:
            headers = {
                'Connection': 'close'
            }
            response = requests.get(url, timeout=4,headers=headers)
            data = response.json()
            proxy_list = data.get("proxy_list", [])
            proxy_list = [json.loads(x) for x in proxy_list]
            return proxy_list
        except:
            # logger.error("请求代理失败！")
            raise

    # 获取代理ip
    def get_proxy(self, num: int = 1, Type='S'):
        '''

        通过控制数量以及获取的代理类型进行获取代理
        S: 短效
        L: 长效
        V: VPN
        '''
        if num<=0:
            num = 1
        if Type == "S":
            url = random.choice(self.proxy_list)+str(num)
        elif Type == "L":
            url = random.choice(self.long_proxy_list)+str(num)
        elif Type == "V":
            logger.error("VPN 代理暂无！")
            return [] if num >1 else {}
        elif Type == 'W':
            return random.choice(waiwang_proxies_list)
        else:
            logger.error("不支持的类型！")
            return [] if num >1 else {}
        try:
            proxy_result = self.get_json(url)
            proxys_list = []
            for proxy in proxy_result:
                proxy_ip = proxy["proxy_ip"]
                Type = proxy["type"]
                if Type == 1:
                    user = proxy["user"]
                    password = self.decrypt(proxy["password"])
                    proxies = {
                        "http": f"http://{user}:{password}@{proxy_ip}",
                        "https": f"http://{user}:{password}@{proxy_ip}",
                    }
                else:
                    proxies = {
                        "http": f"http://{proxy_ip}",
                        "https": f"http://{proxy_ip}",
                    }
                proxys_list.append(proxies)
            if not proxy_result:
                logger.error("数据库代理为空！")
                return [] if num >1 else {}
            else:
                return proxys_list if num >1 else proxys_list[0]
        except:
            logger.exception("获取IP失败！")
            return [] if num >1 else {}

Proxy_IP = Proxy_IP()
if __name__ == '__main__':
    print(Proxy_IP.get_proxy(Type="L"))
